import { useContext, useEffect, useState } from 'react';
import { Context } from './Context';
import Mx from 'mxdraw';

import styles from './workspace.module.less';
import { DrawType } from '../components/tool/config';

const Workspace = () => {
  const { drawMode, setState, drawTool, shapes, guildTool, selectShapIds } = useContext(Context);

  const handlerKeyDown =(evt: KeyboardEvent) => {
    if (['Escape', 'Enter'].includes(evt.key)) {
      if (drawTool && [DrawType.ployLine, DrawType.line].includes(drawTool.drawMode)) {
        drawTool && drawTool.drawEnd();
      } else {
        if (evt.key === 'Escape') {
          setState({ selectShapIds: [] });
        }
      }
    } else if (['Delete', 'Backspace'].includes(evt.key)) {
      // 删除
      if (selectShapIds.length) {
        const otherShaps = shapes.filter(shape => !selectShapIds.includes(shape.id));
        selectShapIds.length = 0;
        shapes.length = 0;
        shapes.push(...otherShaps);
        setState({
          selectShapIds,
          shapes
        });
      }
    }
  };

  useEffect(() => {
    Mx.loadCoreCode().then(async () => {
        // 创建控件对象
        Mx.MxFun.createMxObject({
            canvasId: 'draw_layer'
        });
    })
  }, []);


  useEffect(() => {
    window.addEventListener('keydown', handlerKeyDown);
    return () => {
      window.removeEventListener('keydown', handlerKeyDown);
    };
  }, [drawTool]);

  return (
    <canvas id='draw_layer' />
  );
};

export default Workspace;